/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.juick.mod.api;

import java.util.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author ugnich
 */
public class JuickMessage 
{
    public int MID = 0;
    public int RID = 0;
    public String Text = null;
    public JuickUser User = null;
    public Vector<String> tags = new Vector<String>();
    public int replies = 0;

    public static JuickMessage parseJSON(JSONObject json) throws JSONException {
        JuickMessage jmsg = new JuickMessage();
        jmsg.MID = json.getInt("mid");
        if (json.has("rid")) {
            jmsg.RID = json.getInt("rid");
        }
        jmsg.Text = json.getString("body").replace("&quot;", "\"");
        jmsg.User = JuickUser.parseJSON(json.getJSONObject("user"));

        if (json.has("tags")) {
            JSONArray tags = json.getJSONArray("tags");
            for (int n = 0; n < tags.length(); n++) {
                jmsg.tags.add(tags.getString(n).replace("&quot;", "\""));
            }
        }

        if (json.has("replies")) {
            jmsg.replies = json.getInt("replies");
        }
        return jmsg;
    }

    public String getTags() {
        String t = new String();
        for (Enumeration<String> e = tags.elements(); e.hasMoreElements();) {
            String tag = (String) e.nextElement();
            if (t.length() > 0) {
                t += ' ';
            }
            t += '*' + tag;
        }
        return t;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof JuickMessage)) {
            return false;
        }
        JuickMessage jmsg = (JuickMessage) obj;
        return (this.MID == jmsg.MID && this.RID == jmsg.RID);
    }

    public int compareTo(Object obj) throws ClassCastException {
        if (!(obj instanceof JuickMessage)) {
            throw new ClassCastException();
        }
        JuickMessage jmsg = (JuickMessage) obj;

        if (this.MID != jmsg.MID) {
            if (this.MID > jmsg.MID) {
                return -1;
            } else {
                return 1;
            }
        }

        if (this.RID != jmsg.RID) {
            if (this.RID < jmsg.RID) {
                return -1;
            } else {
                return 1;
            }
        }

        return 0;
    }
}
